package com.repair.security;

import com.repair.entity.User;
import com.repair.service.UserService;
import com.repair.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Lazy;

import java.util.Collections;

@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try {
            String token = (String) authentication.getCredentials();
            String username = jwtUtil.extractUsername(token);

            if (username != null) {
                User user = userService.getByUsername(username);
                if (user != null && jwtUtil.validateToken(token, user)) {
                    return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthenticationToken.class.isAssignableFrom(authentication);
    }

    private String getRoleString(Integer role) {
        switch (role) {
            case 0:
                return "USER";
            case 1:
                return "ADMIN";
            case 2:
                return "REPAIRMAN";
            default:
                return "USER";
        }
    }
} 